<template>
  <el-form ref="ruleFormRef" :model="form" label-width="auto" style="max-width: 600px" :rules="rules">
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name" placeholder="请输入" class="constWidth" />
    </el-form-item>
    <el-form-item label="类型" prop="type">
      <el-select v-model="form.type" placeholder="请选择" class="constWidth">
        <el-option v-for="item in types" :key="item" :label="item" :value="item" />
      </el-select>
    </el-form-item>
    <el-form-item label="日期" prop="date">
      <el-date-picker
        v-model="form.date"
        type="datetime"
        placeholder="请选择日期"
        style="width:250px;"
      />
    </el-form-item>
    <el-form-item label="完成数" prop="totalNum">
      <el-input-number v-model="form.totalNum" :min="0" class="constWidth"/>
    </el-form-item>
    <el-form-item label="正确数" prop="rightNum">
      <el-input-number v-model="form.rightNum" :min="0" class="constWidth"/>
    </el-form-item>
    <el-form-item label="练习时长" prop="testMinute">
      <el-input-number v-model="form.testMinute" :min="0" class="constWidth" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="addRandom(100000)" :loading="loading">随机添加</el-button>
</template>
<script lang="ts">
import { reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { nodeService } from '@/service/index'
interface RuleForm {
  name: string
  date:string | number
  type: string
  rightNum: number
  totalNum: number
  testMinute: number
}
export const types = ['混合运算', '乘加乘减', '带余数除法', '除法', '乘法', '三位数加减', '100以内加减', '20以内加减']
export default {
  emits: ['cancel'],
  props: ['formData'],
  setup(props, context) {
    const form = reactive<RuleForm>({} as RuleForm)
    const rules = reactive<FormRules<RuleForm>>({
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 40, message: '长度2-40个字符', trigger: 'blur' }
      ],
      date: [
        {
          required: true,
          message: '请选择时间',
          trigger: 'change'
        }
      ],
      type: [
        {
          required: true,
          message: '请选择类型',
          trigger: 'change'
        }
      ]
    })
    const ruleFormRef = ref<FormInstance>()
    const submitForm = async(formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          nodeService.post('/add', { ...form, date: new Date(form.date).getTime() }).then((res:any) => {
            ElMessage({
              message: res.data,
              type: 'success'
            })
            resetForm(formEl)
          }).catch((err:any) => {
            ElMessage.error(err.message)
          })
        } else {
          console.log('error submit!', fields)
        }
      })
    }
    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.resetFields()
      context.emit('cancel')
    }
    // 生成随机数
    const getNum = (min: number, max: number) => {
      return Math.floor(Math.random() * (max - min + 1)) + min
    }
    // 随机添加
    const loading = ref(false)
    const addRandom = (num: number) => {
      if (loading.value) {
        return
      }
      loading.value = true
      const names = ['李谦', '李润泽', '李孝笑', '蔡倩', 'oHs1G5a0yJBsDteCtUixQKDyIiKc', 'oHs1G5a8Oi8rvtf74Wbh3qG8qoZE', 'oHs1G5afztGbDs-jtAFhaedqGwPk', 'oHs1G5aK6-2FZ-sDxptMFoFupVlw', 'oHs1G5al1nIbNhelCWWpy4xCEcS0', 'oHs1G5ayuu8w7q5NtrF1xULwJKzo', 'oHs1G5b04k9vFEoQtbljcsEiof30', 'oHs1G5b0l9VRtzWocqFzUdNrPUmM', 'oHs1G5b1XPZDsJ05U2MQbXifVorQ', 'oHs1G5b6Fq642roJbwUiaITmYaws', 'oHs1G5b7z7cJEKzwd1TI_eM-Il04', 'oHs1G5bHgT44q_JN2lMCK-zpWtX4', 'oHs1G5bhnTKPITUdv8Tpr7wYIvVI', 'oHs1G5bnk1yRFVnfpNieOgdC0Iiw', 'oHs1G5bPyoX8F1H94r1cexvC7--0', 'oHs1G5bvTYy0ry3Kxg90U6Id1lW8', 'oHs1G5bwnDpszHREGrqbyxR-6CYs', 'oHs1G5c3s5Cyr65FFk2ctshsbDzQ', 'oHs1G5cds1FFQaX9X9Ts6XMBjOAs', 'oHs1G5cf-Aqk2WJgLDqK7bYF9jGE', 'oHs1G5csjZ3e0h78sW8uGheLUXGU', 'oHs1G5dgGgmnj4Jb3WeFeZ33iFr4', 'oHs1G5dN3Nurf98-dktaUMEwlLrg', 'oHs1G5do9Rz-erAOlRw9nIjbyWDs', 'oHs1G5dPf_6cMRzlB7AmufFGhuzg', 'oHs1G5e4vySjll70XgaqFPjdIkrA', 'oHs1G5e9ix1NxtpAFqlRqnaKIXko', 'oHs1G5eEMifTazkMnLoSM4zIYC74', 'oHs1G5eKC6KjylCrcbzokjvdDLx8', 'oHs1G5eOqWChlzgSIA3BF6A4WDGo', 'oHs1G5ePwr8PuiATVhCzogcY7G_s', 'oHs1G5eVBxPiymdcvfXLRjWxt9F8', 'oHs1G5ezSPKUiX659HBkxfKoDVvU']
      const promiseArr = []
      for (let i = 0; i < num; i++) {
        const mid: RuleForm = {} as RuleForm
        mid.type = types[getNum(0, 7)]
        mid.name = names[getNum(0, 36)]
        mid.rightNum = getNum(10, 100)
        mid.totalNum = getNum(mid.rightNum, mid.rightNum + 20)
        mid.date = new Date().getTime() - getNum(0, 300000) * 1000
        mid.testMinute = getNum(30, 59)
        promiseArr.push(mid)
      }
      nodeService.post('/batchAdd', promiseArr).then((res:any) => {
        ElMessage({
          message: res.data,
          type: 'success'
        })
        context.emit('cancel')
      }).catch((err:any) => {
        ElMessage.error(err.message)
      }).finally(() => {
        loading.value = false
      })
    }
    watch(props.formData, (newData) => {
      for (const i in newData.row) {
        form[i as 'name'] = newData.row[i]
      }
    }, { immediate: true })
    return { form, rules, ruleFormRef, submitForm, resetForm, types, addRandom, loading }
  }
}

</script>
<style lang="less" scoped>
 .constWidth{
  width:250px;
 }
</style>
